import { v4 as uuidv4 } from 'uuid'
import CosAuth from '@/utils/cos-auth'

const platform = getPlatform()

// cos上传: 临时签名缓存
let stsCache: any = $ref({})
// cos上传: 用临时签名构造请求头
const authData = $computed(() => {
  return {
    XCosSecurityToken: stsCache.credentials.sessionToken,
    Authorization: CosAuth({
      SecretId: stsCache.credentials.tmpSecretId,
      SecretKey: stsCache.credentials.tmpSecretKey,
      Method: 'POST',
      Pathname: '/',
    }),
  }
})
// cos上传: 从服务器获取临时签名
const getCredentials = async () => {
  if (!!stsCache.expiredTime && stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
    return
  }
  stsCache = {}
  const resp = await Fetch('/api/cos/getCredential')
  if (resp.status !== 200 || resp.data.code !== 0) {
    console.log(resp)
    uni.showModal({ title: '上传失败', content: resp.data.msg, showCancel: false })
    return
  }
  stsCache = resp.data.result
}
// cos上传: post方式
const postCosFile = async (filePath, key) => {
  await getCredentials()
  await uploadFile({
    url: cosUrl,
    name: 'file',
    filePath,
    formData: {
      'key': key,
      'success_action_status': 200,
      'Signature': authData.Authorization,
      'x-cos-security-token': authData.XCosSecurityToken,
      'Content-Type': '',
    },
    fail(res) {
      uni.showModal({ title: '上传失败', content: JSON.stringify(res), showCancel: false })
    },
  })
}
// 上传选择的文件到 cos。视频的 tempFile 里没有 path，需要额外的 path 传参
export const uploadCosFile = async (tempFile, filePath) => {
  let fileName = `${cosDir}/${filePath.slice(filePath.lastIndexOf('/') + 1)}`
  if (platform === 'H5') {
    const fileExt = tempFile.name.slice(tempFile.name.lastIndexOf('.'))
    fileName = `${cosDir}/${uuidv4()}${fileExt}`
  }
  await postCosFile(filePath, fileName)
  // 上传后的 cos 文件地址
  // console.log(`${cosUrl}/${fileName}`)
  return `${cosUrl}/${fileName}`
}
